#include "nameserver.h"
#include <iostream>
using namespace std;

NameServer::NameServer( Printer &prt, unsigned int numVendingMachines, unsigned int numStudents ) {

	this->numVendingMachines = numVendingMachines;
	this->numStudents = numStudents;
  this->prt = &prt;
  machineList = new VendingMachine *[numVendingMachines];
  sl = new unsigned int[numStudents];
  for(int i = 0; i < numStudents; i++) {
    sl[i] = i;
  }
  prt.print(Printer::NameServer, 'S');
  curIndex_reg = 0;
}

void NameServer::VMregister( VendingMachine *vendingmachine ) {
  prt->print(Printer::NameServer, 'R', (vendingmachine->getId()));
  machineList[ curIndex_reg ] = vendingmachine;
  if (curIndex_reg == numVendingMachines - 1) {
    curIndex_reg = 0;
  } else {
    curIndex_reg += 1;
  }
}
  
VendingMachine *NameServer::getMachine( unsigned int id ) {
  unsigned int i = sl[id] % numVendingMachines;
  prt->print(Printer::NameServer, 'N', id, machineList[ i ]->getId());
  sl[id] += 1;
  return machineList[ i ];
}

NameServer::~NameServer() {
  prt->print(Printer::NameServer, 'F');
  delete [] machineList;
  delete [] sl;
}

VendingMachine **NameServer::getMachineList() {
  /*unsigned int len = machineList.size();
  typedef VendingMachine* ven_p;
  ven_p *ans = new ven_p[len];
  for(int i = 0; i < len; i++) {
    ans[i] = machineList[i];
  }
  return ans;*/
  return machineList;
}